package com.netease.nim.chatroom.demo.meeting.fragment;

import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.chatroom.demo.DemoCache;
import com.netease.nim.chatroom.demo.R;
import com.netease.nim.chatroom.demo.base.ui.TFragment;
import com.netease.nim.chatroom.demo.base.util.ScreenUtil;
import com.netease.nim.chatroom.demo.meeting.activity.ChatRoomActivity;
import com.netease.nim.chatroom.demo.meeting.doodle.ActionTypeEnum;
import com.netease.nim.chatroom.demo.meeting.doodle.DoodleView;
import com.netease.nim.chatroom.demo.meeting.doodle.OnlineStatusObserver;
import com.netease.nim.chatroom.demo.meeting.doodle.SupportActionType;
import com.netease.nim.chatroom.demo.meeting.doodle.TransactionCenter;
import com.netease.nim.chatroom.demo.meeting.doodle.action.MyPath;
import com.netease.nim.chatroom.demo.meeting.helper.ChatRoomMemberCache;
import com.netease.nim.chatroom.demo.meeting.helper.VideoListener;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.rts.RTSCallback;
import com.netease.nimlib.sdk.rts.RTSManager2;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Looper.getMainLooper;

/**
 * Created by hzxuwen on 2016/10/27.
 */

public class ChatRoomRTSFragment extends TFragment implements View.OnClickListener, VideoListener, OnlineStatusObserver {
    private View rootView;
    private DoodleView doodleView; // 画板
    // 控制条
    private TextView clearAllBtn;
    private TextView playbackBtn;
    private TextView chooseColorBtn;
    private View joinTipText;
    // 调色盘
    private ViewGroup palleteLayout;
    private ImageView blackImage;
    private ImageView redImage;
    private ImageView yellowImage;
    private ImageView greenImage;
    private ImageView blueImage;
    private ImageView purpleImage;

    // data
    private String sessionId; // 白板sessionId
    private ChatRoomInfo roomInfo;
    private HashMap<Integer, Integer> colorChoosedMap = new HashMap<>();
    private HashMap<Integer, Integer> colorMap = new HashMap<>();
    private int choosedColor = R.drawable.choose_black_circle_shape;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.chat_room_rts_fragment, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        sessionId = ((ChatRoomActivity) getActivity()).getSessionId();
        roomInfo = ((ChatRoomActivity)getActivity()).getRoomInfo();
        initData();
        findViews();
        initDoodleView(null);
        setListener();
        registerObservers(true);
    }

    public void onCurrent() {
        initView();
        if (TextUtils.isEmpty(sessionId)) {
            sessionId = ((ChatRoomActivity) getActivity()).getSessionId();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        doodleView.onResume();
    }

    @Override
    public void onDestroy() {
        if (doodleView != null) {
            doodleView.end();
        }
        registerObservers(false);
        super.onDestroy();
    }

    private void registerObservers(boolean register) {
        ChatRoomMemberCache.getInstance().registerMeetingControlObserver(meetingControlObserver, register);
        TransactionCenter.getInstance().registerOnlineStatusObserver(sessionId, this);
    }

    ChatRoomMemberCache.MeetingControlObserver meetingControlObserver = new ChatRoomMemberCache.MeetingControlObserver() {
        @Override
        public void onAccept(String roomID) {

        }

        @Override
        public void onReject(String roomID) {
            if (!roomID.equals(roomInfo.getRoomId())) {
                return;
            }
            ChatRoomMemberCache.getInstance().setRTSOpen(false);
            initView();
        }

        @Override
        public void onPermissionResponse(String roomId, List<String> accounts) {

        }

        @Override
        public void onSaveMemberPermission(String roomID, List<String> accounts) {

        }

        @Override
        public void onSendMyPermission(String roomID, String toAccount) {

        }

        @Override
        public void onHandsUp(String roomID, String account) {

        }

        @Override
        public void onHandsDown(String roomID, String account) {

        }

        @Override
        public void onStatusNotify(String roomID, List<String> accounts) {

        }
    };

    private void initData() {
        colorChoosedMap.put(R.id.black_color_image, R.drawable.choose_black_circle_shape);
        colorChoosedMap.put(R.id.red_color_image, R.drawable.choose_red_circle_shape);
        colorChoosedMap.put(R.id.yellow_color_image, R.drawable.choose_yellow_circle_shape);
        colorChoosedMap.put(R.id.green_color_image, R.drawable.choose_green_circle_shape);
        colorChoosedMap.put(R.id.blue_color_image, R.drawable.choose_blue_circle_shape);
        colorChoosedMap.put(R.id.purple_color_image, R.drawable.choose_purple_circle_shape);

        colorMap.put(R.id.black_color_image, Color.BLACK);
        colorMap.put(R.id.red_color_image, getResources().getColor(R.color.color_red_d1021c));
        colorMap.put(R.id.yellow_color_image, getResources().getColor(R.color.color_yellow_fddc01));
        colorMap.put(R.id.green_color_image, getResources().getColor(R.color.color_green_7dd21f));
        colorMap.put(R.id.blue_color_image, getResources().getColor(R.color.color_blue_228bf7));
        colorMap.put(R.id.purple_color_image, getResources().getColor(R.color.color_purple_9b0df5));
    }

    private void findViews() {
        // 画板
        doodleView = findView(R.id.doodle_view);
        // 控制条
        clearAllBtn = findView(R.id.clear_all_btn);
        playbackBtn = findView(R.id.play_back_btn);
        chooseColorBtn = findView(R.id.choose_color_btn);
        if (roomInfo != null && roomInfo.getCreator().equals(DemoCache.getAccount())) {
            clearAllBtn.setVisibility(View.VISIBLE);
        } else {
            clearAllBtn.setVisibility(View.GONE);
        }
        joinTipText = findView(R.id.join_tip_text);
        // 调色盘
        palleteLayout = findView(R.id.palette_layout);
        blackImage = findView(R.id.black_color_image);
        redImage = findView(R.id.red_color_image);
        yellowImage = findView(R.id.yellow_color_image);
        greenImage = findView(R.id.green_color_image);
        blueImage = findView(R.id.blue_color_image);
        purpleImage = findView(R.id.purple_color_image);
    }

    private void setListener() {
        clearAllBtn.setOnClickListener(this);
        playbackBtn.setOnClickListener(this);
        chooseColorBtn.setOnClickListener(this);
        // 调色盘
        palleteLayout.setOnClickListener(this);
        blackImage.setOnClickListener(colorClickListener);
        redImage.setOnClickListener(colorClickListener);
        yellowImage.setOnClickListener(colorClickListener);
        greenImage.setOnClickListener(colorClickListener);
        blueImage.setOnClickListener(colorClickListener);
        purpleImage.setOnClickListener(colorClickListener);
    }

    // 初始化是否开启白板
    private void initView() {
        if (ChatRoomMemberCache.getInstance().isRTSOpen()) {
            clearAllBtn.setBackgroundResource(R.drawable.chat_room_clear_all_selector);
            playbackBtn.setBackgroundResource(R.drawable.chat_room_play_back_selector);
            chooseColorBtn.setBackgroundResource(choosedColor);
            clearAllBtn.setEnabled(true);
            playbackBtn.setEnabled(true);
            chooseColorBtn.setEnabled(true);
            doodleView.setEnableView(true);
            joinTipText.setVisibility(View.GONE);
        } else {
            clearAllBtn.setBackgroundResource(R.drawable.ic_clear_all_disable);
            playbackBtn.setBackgroundResource(R.drawable.ic_play_back_disable);
            chooseColorBtn.setBackgroundResource(R.drawable.ic_choose_color_disable);
            clearAllBtn.setEnabled(false);
            playbackBtn.setEnabled(false);
            chooseColorBtn.setEnabled(false);
            doodleView.setEnableView(false);
            joinTipText.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        if (v == clearAllBtn) {
            doodleView.clear();
        } else if (v == playbackBtn) {
            doodleView.paintBack();
        } else if (v == chooseColorBtn) {
            palleteLayout.setVisibility(View.VISIBLE);
        } else if (v == palleteLayout) {
            palleteLayout.setVisibility(View.GONE);
        }
    }

    View.OnClickListener colorClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            palleteLayout.setVisibility(View.GONE);
            choosedColor = colorChoosedMap.get(v.getId());
            chooseColorBtn.setBackgroundResource(choosedColor);
            doodleView.setPaintColor(colorMap.get(v.getId()));
        }
    };


    private void endSession() {
        RTSManager2.getInstance().leaveSession(sessionId, new RTSCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
            }

            @Override
            public void onFailed(int code) {
                Toast.makeText(getContext(), "挂断请求错误，code：" + code, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable exception) {

            }
        });
    }

    /**
     * ***************************** 画板 ***********************************
     */

    private void initDoodleView(String account) {
        Toast.makeText(getContext(), "init doodle success", Toast.LENGTH_SHORT).show();
        // add support ActionType
        SupportActionType.getInstance().addSupportActionType(ActionTypeEnum.Path.getValue(), MyPath.class);

        doodleView.init(sessionId, account, DoodleView.Mode.BOTH, Color.WHITE, getContext());

        doodleView.setPaintSize(3);
        doodleView.setPaintType(ActionTypeEnum.Path.getValue());

        // adjust paint offset
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Rect frame = new Rect();
                getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                int statusBarHeight = frame.top;
                Log.i("Doodle", "statusBarHeight =" + statusBarHeight);

                int marginTop = doodleView.getTop();
                Log.i("Doodle", "doodleView marginTop =" + marginTop);

                int marginLeft = doodleView.getLeft();
                Log.i("Doodle", "doodleView marginLeft =" + marginLeft);

                float offsetX = marginLeft;
                float offsetY = statusBarHeight + marginTop + ScreenUtil.dip2px(220) + ScreenUtil.dip2px(40);

                doodleView.setPaintOffset(offsetX, offsetY);
                Log.i("Doodle", "client1 offsetX = " + offsetX + ", offsetY = " + offsetY);
            }
        }, 50);
    }

    @Override
    public void onVideoOn(String account) {

    }

    @Override
    public void onVideoOff(String account) {

    }

    @Override
    public void onTabChange(boolean notify) {

    }

    @Override
    public void onKickOutSuccess(String account) {

    }

    @Override
    public void onUserLeave(String account) {

    }

    @Override
    public void onReportSpeaker(Map<String, Integer> map) {

    }

    @Override
    public void onAcceptConfirm() {
        initView();
    }

    /*************************** 网络状态 *********************/

    @Override
    public boolean onNetWorkChange(boolean isCreator) {
        // 断网重连。主播断网重连上来，给观众发自己的同步数据
        // 观众先清空本地
        if (isCreator) {
            doodleView.sendSyncPrepare();
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    doodleView.sendSyncData(null);
                }
            }, 50);
        } else {
            initView();
            doodleView.clearAll();
        }
        return true;
    }
}
